<?php
namespace app\model;

use app\model\BaseModel;
use app\model\Source;

class AdminUser extends BaseModel{
    // 检测管理元是否存在
    public function testAdminUserExis($name = ''){
        return !!$this->where('username',$name)->count();
    }
    // 用户登录
    public function loginUser($username = '',$password = ''){
        if($this->testAdminUserExis($username)){
            $user = $this->where('username',$username)->findOrEmpty();
            if($user['password'] == $this->encode(md5($password),$user['vi'])){
                return [
                    'token'     => $this->encode($user['id'].'|'.$username),
                    'nickname'  => $user['nickname'],
                    'username'  => $user['username'],
                    'headimage' => $user['headimage'],
                    'create_at' => $user['create_at']
                ];
            }
        }
        return false;
    }
    // 生成一个管理员用户并添加到数据库
    public function generateAdmin($username,$password,$nickname='管理员',$headimage = 1){
        if(!$this->testAdminUserExis($username)){
            return false;
        }
        $vi = $this->create_password(16);
        return $this->insert([
            'nickname' => $nickname,
            'username' => $username,
            'password' => $this->encode(md5($password),$vi),
            'headimage'=> $headimage,
            'vi'       => $vi
        ]);
    }
    /**
     * 检测id与username是否匹配
    */
    public function testUserAndId($id , $username){
        return !!$this->where(['id'=>$id,'username' => $username,'state'=>1])->count();
    }
    // 建立关联关系
    public function source(){
        return $this->hasOne(Source::class,'user_id');
    }
    /**
     * 获取自己的基本资料
     * @param number 自身的ID
     * */
    public function getMyselfProfile($id){
        return $this->field('wx_admin_user.id,nickname,username,email,source.name,source.type,source.href')
                    ->where('wx_admin_user.id',$id)
                    ->alias('admin_user')
                    ->join(['wx_source'=>'source'],'admin_user.headimage = source.id')
                    ->where(['source.state'=>1,'is_delete' => NULL])
                    ->findOrEmpty();
    }
    /**
     * 修改密码
     * 获取被修改者的 用户 id
    */
    public function alterPassword($id,$newPassword = '12345678'){
        $user = $this->where(['id' => $id])->findOrEmpty();
        if(!array_key_exists('password',$user) || array_key_exists('vi',$user)){
            return ['code' => 404, 'msg' => '未找到用户'];
        }
        $vi = $user['vi'];
        $user['password'] = $this->encode(md5(sha1(md5($newPassword))),$vi);
        $data = $this->save($user);
        if($data){
            return ['code' => 200, 'msg' => '修改成功！'];
        }
        return ['code' => 202, 'msg' => '数据已修改，请重试！'];
    }
}